<?php

namespace app\modules\user\controllers;

use yii;
use app\libs\ApiControl;
use app\libs\Method;
use app\modules\admin\models\Apply;
use app\modules\user\models\User;
use app\modules\admin\models\Message;
use app\modules\admin\models\Tactics;


class UserController extends ApiControl
{
    public $layout = 'user';

    public $enableCsrfValidation = false;
    function init (){
        parent::init();
        include_once($_SERVER['DOCUMENT_ROOT'].'/../libs/ucenter/ucenter.php');
    }

    public function actionIndex()
    {
        $page = Yii::$app->request->get('page',1);
        $beginTime = strtotime(Yii::$app->request->get('beginTime',''));
        $endTime = strtotime(Yii::$app->request->get('endTime',''));
        $id  = Yii::$app->request->get('id','');
        $phone  = Yii::$app->request->get('phone','');
        $email  = Yii::$app->request->get('email','');
        $userName  = Yii::$app->request->get('userName','');
        $nickname  = Yii::$app->request->get('nickname','');
        $where="1=1";
        if($beginTime){
            $where .= " AND createTime>=$beginTime";
        }
        if($endTime){
            $where .= " AND createTime<=$endTime";
        }
        if($id){
            $where .= " AND id = $id";
        }
        if($phone){
            $where .= " AND phone = '$phone'";
        }
        if($email){
            $where .= " AND email = '$email'";
        }
        if($userName){
            $where .= " AND userName = '$userName'";
        }
        if($nickname){
            $where .= " AND nickname = '$nickname'";
        }

        $model = new User();

        $data = $model->getUsers($where,10,$page);
        // f_d($data);
        foreach ($data['data'] as $key => $value) {
            $ucInfo = uc_user_info($value['uid']);
            // var_dump($ucInfo);
            $data['data'][$key]['source'] = $ucInfo['source'];
            $data['data'][$key]['city'] = $ucInfo['city'];
            $data['data'][$key]['reffer'] = $ucInfo['reffer'];
        }
        // f_d($data);
        $page = Method::getPagedRows(['count'=>$data['count'],'pageSize'=>10, 'rows'=>'models']);
        // foreach($data['data'] as $k => $v){
        //     $integral = uc_user_integral($v['username']);
        //     $data['data'][$k]['integral'] = $integral['integral']?$integral['integral']:0;
        //     $data['data'][$k]['integralDetails'] = $integral['details'];
        // }
        $controller= Yii::$app->controller->id;
        $module = Yii::$app->controller->module->id;
        $block = Yii::$app->db->createCommand("select action,name from  {{%node}} where module='$module' and controller= '$controller' and  level!=1")->queryAll();
//        var_dump($block);die;
        return $this->render('index',['page' => $page,'data' => $data['data'],'block'=>$block]);
    }




    public function actionApply()
    {
        // 公开课的ID，报名者电话，的取到title
        $data = Yii::$app->db->createCommand("select c.*,i.title from {{%class_apply}} c join {{%info}} i on c.pubclass_id=i.id ")->queryALL();
        return $this->render('apply',['data'=>$data]);
    }
    public function actionApply_edit()
    {
        $id= Yii::$app->request->get('id', '');
        if(!$_POST){
            return $this->render('apply_edit',['id'=>$id]);
        }else{
            $data['id'] = Yii::$app->request->post('id', '');
            $data['address'] = Yii::$app->request->post('address', '');
            $model = new Apply();
            $re = $model->updateAll($data,'id=:id', array(':id'=> $data['id']));
            if ($re) {
                $this->redirect('apply');
            } else {
                echo '<script>alert("数据添加/修改失败，请重试");history.go(-1);</script>';
                die;
            }
        }


    }
    public function actionMessage()
    {
        // 公开课的ID，报名者电话，的取到title
       $data = Yii::$app->db->createCommand("select * from {{%message}}")->queryALL();
        return $this->render('message',['data'=>$data]);
    }
    public function actionSuggest_edit()
    {
        if (!$_POST) {
            $id = Yii::$app->request->get('id', '');
            if (empty($id)) {
                return $this->render('suggest_edit');
            } else {
                $data = Yii::$app->db->createCommand("select * from {{%tactics}} where id=" . $id)->queryOne();
                $data['models']=explode('-',$data['major'])[0];
                $data['major']=explode('-',$data['major'])[1];
                return $this->render('suggest_edit', ['data' => $data]);
            }

        } else {
            $tactics = new Tactics();
            $data["major"]=Yii::$app->request->post("models",'')."-".Yii::$app->request->post("major",'');
            $data["min"]=Yii::$app->request->post("min",'');
            $data["max"]=Yii::$app->request->post("max",'');
            $data["suggestion"]=Yii::$app->request->post("suggestion",'');

            if (empty($data['id'])) {
                $re = Yii::$app->db->createCommand()->insert("{{%tactics}}", $data)->execute();
            } else {
                // 修改时，提交id
                $re = $tactics->updateAll($data, 'id=:id', array(':id' => $data['id']));
            }
            if ($re) {
                $this->redirect('suggest');
            } else {
                echo '<script>alert("数据添加/修改失败，请重试");history.go(-1);</script>';
                die;
            }

        }

    }
    public function actionSuggest()
    {
        // 公开课的ID，报名者电话，的取到title
        $data = Yii::$app->db->createCommand("select * from {{%tactics}}")->queryALL();
        return $this->render('suggest',['data'=>$data]);
    }
    public function actionDel3()
    {
        $id = Yii::$app->request->get('id', '');
        $re = Tactics::deleteAll("id=:id", array(':id' => $id));
        if ($re) {
            echo true;
        }
    }
    public function actionCheck()
    {
        $data['flag']= Yii::$app->request->post('flag', '');
        $data['id'] = Yii::$app->request->post('id', '');
//        $data['address'] = Yii::$app->request->post('address', '');
        $model = new Message();
        $re = $model->updateAll($data,'id=:id', array(':id'=> $data['id']));
        if($re){
            $res['code'] = 1;
            $res['message'] = '修改成功';
        } else {
            $res['code'] = 0;
            $res['message'] = '修改失败';
        }
        die(json_encode($res));
    }

    /**
     * 添加用户
     * @return string
     * @throws yii\db\Exception
     * @Obelisk
     */
    public function actionAdd(){
        if($_POST){
            $user = Yii::$app->request->post('user');
            foreach($user as $k=>$v){
                if($k != 'image' && $v != ''){
                    $sign = User::find()->where("$k='$v'")->one();
                    if($sign){
                        die('<script>alert("'.$k.'已被使用");history.go(-1);</script>');
                    }
                }
            }
            $userPass = Yii::$app->request->post('userPass');
            $uid = uc_user_register($user['userName'],md5($userPass),$user['email'],$user['phone'],'托福Pc后台',time());
            if($uid == -3){
                die('<script>alert("用户名已经存在");history.go(-1);</script>');
            }
            elseif($uid == -6){
                die('<script>alert("邮箱已经被注册");history.go(-1);</script>');
            }elseif($uid == -7){
                die('<script>alert("电话已经被注册");history.go(-1);</script>');
            }
            if($uid > 0){
                $remark = Yii::$app->request->post('remark');
                $user['remark'] = $remark;
                $user['userPass'] = md5($userPass);
                $user['createTime'] = time();
                $sign = Yii::$app->db->createCommand()->insert('{{%user}}',$user)->execute();
                if($sign){
                    $this->redirect('/user/user/index');
                }else{
                    die('<script>alert("保存失败，请重试");history.go(-1);</script>');
                }
            }else{
                die('<script>alert("保存失败，请重试");history.go(-1);</script>');
            }

        }else{
            return $this->render('add');
        }
    }

    /**
     * 删除用户
     * @return string
     * @Obelisk
     */
    public function actionDelete(){
        $id = Yii::$app->request->get('id');
        $url = $_GET['url'];
        User::findOne($id)->delete();
        $this->redirect($url);
    }

    /**
     * 修改用户信息
     * @return string
     * @Obelisk
     */
    public function actionUpdata(){
        if($_POST){
            $user = Yii::$app->request->post('user');
            $id = Yii::$app->request->post('id');
            foreach($user as $k=>$v){
                if($k != 'image' && $v != ''){
                    $sign = User::find()->where("$k='$v' AND id!=$id")->one();
                    if($sign){
                        die('<script>alert("'.$k.'已被使用");history.go(-1);</script>');
                    }
                }
            }
            $sign = User::find()->where("phone='{$user['phone']}' AND id=$id")->one();
            if(!$sign){
                $status = uc_user_checkphone($user['phone']);
                if ($status == -7) {
                    die('<script>alert("该手机已被绑定");history.go(-1);</script>');
                }
            }
            $sign = User::find()->where("email='{$user['email']}' AND id=$id")->one();
            if(!$sign){
                $sign = uc_user_checkemail($user['email']);
                if ($sign == -6) {
                    die('<script>alert("该邮箱已被绑定");history.go(-1);</script>');
                }
            }
            $sign = User::findOne($id);
            $userPass = Yii::$app->request->post('userPass');
            $remark = Yii::$app->request->post('remark');
            $user['remark'] = $remark;
            if($sign->userPass != $userPass){
                $user['userPass'] = md5($userPass);
            }
            uc_user_edit($sign->userName,'',$user['userPass'],$user['email'],$user['phone'],1);
            $sign = User::updateAll($user,"id=$id");
            if($sign){
                $this->redirect('/user/user/index');
            }else{
                die('<script>alert("保存失败，请重试");history.go(-1);</script>');
            }
        }else{
            $id = Yii::$app->request->get('id');
            $data = User::findOne($id);
            return $this->render('update',['data' => $data,'id' => $id]);
        }
    }

}